package cn.topevery.garden.wapi.exception;

import hw.topevery.framework.web.HttpResultCode;
import hw.topevery.framework.web.JsonResult;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@ControllerAdvice
public class GreGolbalException {

    /**
     * 捕获一般异常
     * 捕获未知异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonResult defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
        return JsonResult.error(e.getMessage());
    }

    /***
     * 404处理
     * @param e
     * @return
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public JsonResult notFountHandler(HttpServletRequest request, NoHandlerFoundException e) {
        return JsonResult.error(e.getMessage(), HttpResultCode.NOT_FOUND.getCode());
    }
}
